package mi.payment;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.DisplayMetrics;

import com.sunmi.pay.hardware.aidl.emv.EMVOpt;
import com.sunmi.pay.hardware.aidl.pinpad.PinPadOpt;
import com.sunmi.pay.hardware.aidl.readcard.ReadCardOpt;
import com.sunmi.pay.hardware.aidl.security.SecurityOpt;
import com.sunmi.pay.hardware.aidl.system.BasicOpt;
import com.sunmi.pay.hardware.aidlv2.emv.EMVOptV2;
import com.sunmi.pay.hardware.aidlv2.pinpad.PinPadOptV2;
import com.sunmi.pay.hardware.aidlv2.readcard.ReadCardOptV2;
import com.sunmi.pay.hardware.aidlv2.security.SecurityOptV2;
import com.tencent.bugly.crashreport.CrashReport;

import java.util.Locale;

import lainey.ui.utils.CrashHandler;
import lainey.ui.utils.LogUtil;
import mi.payment.constants.Configs;
import mi.payment.db.UserInfoModel;
import mi.payment.ui.other.CacheHelper;
import mi.payment.utils.Config;
import mi.payment.utils.I18NUtils;
import mi.payment.utils.print.DataPrinterKernel;
import mi.payment.utils.props.LoadConfigFileUtils;
import mi.payment.utils.secure.TerminalSecure;
import sunmi.paylib.SunmiPayKernel;
import sunmi.payment.ui.dialog.SdkStateDialog;
import sunmi.sunmiui.utils.Adaptation;

public class MyApplication extends Application {

    public static Context context;

    public static MyApplication app;

    public EMVOpt emvOpt;
    public PinPadOpt pinPadOpt;
    public ReadCardOpt readCardOpt;
    public BasicOpt basicOptBinder;
    public SecurityOpt securityOpt;
    public SunmiPayKernel sunmiPayKernel;

    public EMVOptV2 mEMVOptV2;
    public PinPadOptV2 mPinPadOptV2;
    public SecurityOptV2 mSecurityOptV2;
    public ReadCardOptV2 mReadCardOptV2;

    public String language;
    private SdkStateDialog sdkStateDialog;

    private Handler mainHandler;

    public void post(Runnable run) {
        if (mainHandler == null) return;
        mainHandler.post(run);
    }

    public Handler getMainHandler() {
        if (mainHandler == null) {
            Looper mainLooper = Looper.getMainLooper();
            mainHandler = new Handler(mainLooper);
        }
        return mainHandler;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
        context = getApplicationContext();

        Config.init();
        Adaptation.init(this);
        CrashHandler.getInstance().init();

        initLocaleLanguage();

        Looper mainLooper = Looper.getMainLooper();
        mainHandler = new Handler(mainLooper);

        TerminalSecure.initKeyIndex();

        DataPrinterKernel.INSTANCE().init();

        switch (BuildConfig.BUILD_TYPE) {
            case "release":
                switch (BuildConfig.FLAVOR) {
                    case "lePos":
                        CrashReport.initCrashReport(this, "f15e810daa", true);
                        break;
                    case "allinPay":
                        CrashReport.initCrashReport(this, "4a883595bf", true);
                        break;
                    default:
                        CrashReport.initCrashReport(this, "8b1d23ee71", true);
                        break;
                }
                break;
            case "debug":
                break;
        }

        UserInfoModel.getInstance().initTable();

        showSdkStateDialog(null);
        // 绑定SDK服务
        bindSDKService();
        handler.sendEmptyMessageDelayed(1, 3 * 1000);

        // 加载默认设置文件
        AsyncTask.execute(
                new Runnable() {

                    @Override
                    public void run() {
                        LoadConfigFileUtils.getInstance().loadingConfigFile();
                    }

                }
        );
        language = I18NUtils.getCurrentLanguage(this);
    }

    private void bindSDKService() {
        sunmiPayKernel = SunmiPayKernel.getInstance();
        sunmiPayKernel.initPaySDK(this, mConnectCallback);
    }

    private void showSdkStateDialog(int resId) {
        String text = getString(resId);
        showSdkStateDialog(text);
    }

    private void showSdkStateDialog(String text) {
        boolean judge = sdkStateDialog != null && sdkStateDialog.isShowing();
        if (judge) {
            sdkStateDialog.dismiss();
        }
        sdkStateDialog = new SdkStateDialog(this, text);
        sdkStateDialog.show();
    }

    private SunmiPayKernel.ConnectCallback mConnectCallback = new SunmiPayKernel.ConnectCallback() {

        @Override
        public void onConnectPaySDK() {
            try {
                emvOpt = sunmiPayKernel.mEMVOpt;
                pinPadOpt = sunmiPayKernel.mPinPadOpt;
                readCardOpt = sunmiPayKernel.mReadCardOpt;
                basicOptBinder = sunmiPayKernel.mBasicOpt;
                securityOpt = sunmiPayKernel.mSecurityOpt;

                mEMVOptV2 = sunmiPayKernel.mEMVOptV2;
                mPinPadOptV2 = sunmiPayKernel.mPinPadOptV2;
                mReadCardOptV2 = sunmiPayKernel.mReadCardOptV2;
                mSecurityOptV2 = sunmiPayKernel.mSecurityOptV2;

                if (sdkStateDialog != null) {
                    sdkStateDialog.dismiss();
                }
                if (handler != null) {
                    handler.removeCallbacksAndMessages(null);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onDisconnectPaySDK() {
            try {
                emvOpt = null;
                pinPadOpt = null;
                readCardOpt = null;
                basicOptBinder = null;
                sunmiPayKernel = null;
                showSdkStateDialog(R.string.sdk_state_disconnected);
                handler.sendEmptyMessage(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    };

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (emvOpt == null) {
                bindSDKService();
                handler.sendEmptyMessageDelayed(1, 3 * 1000);
            } else {
                handler.removeCallbacksAndMessages(null);
            }
        }

    };

    public static void initLocaleLanguage() {
        Resources resources = MyApplication.getContext().getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        Configuration config = resources.getConfiguration();
        int showLanguage = CacheHelper.getCurrentLanguage();
        if (showLanguage == Constant.LANGUAGE_AUTO) {
            config.locale = Resources.getSystem().getConfiguration().locale;
            LogUtil.e(Configs.TAG, config.locale.getCountry() + "---这是系统语言");
        } else if (showLanguage == Constant.LANGUAGE_CH_CN) {
            config.locale = Locale.SIMPLIFIED_CHINESE;
            LogUtil.e(Configs.TAG, "这是中文");
        } else {
            LogUtil.e(Configs.TAG, "这是英文");
            config.locale = Locale.ENGLISH;
        }
        resources.updateConfiguration(config, dm);
    }

    public static MyApplication getInstance() {
        return app;
    }

    public static Context getContext() {
        return context;
    }


}
